package cn.hd01.job;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import cn.hd01.common.BaseConstant;
import cn.hd01.repository.entity.BookRecord;
import cn.hd01.repository.entity.Customer;
import cn.hd01.service.BookRecordService;
import cn.hd01.service.CustomerService;
import cn.hd01.sms.SmsService;

/**
 * 预约记录短信提醒
 * @author Bill
 *
 */
@Component
public class SmsBookRecordJob {
	
	@Value("${before.book.remind.hour}")
	private int beforeRemainHour;
	
	@Autowired
	private SmsService smsService;
	
	@Autowired
	private BookRecordService bookRecordService;
	
	@Autowired
	private CustomerService customerService;
	
	private static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
	
	private static SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	
	@Scheduled(fixedRate=300000)
	public void sendSms(){
		Calendar c = Calendar.getInstance();
		c.add(Calendar.HOUR_OF_DAY, beforeRemainHour);
		List<BookRecord> list = bookRecordService.findSmsRecord(sdf2.format(new Date()), sdf2.format(c.getTime()));
		
		if(!CollectionUtils.isEmpty(list)){
			for(BookRecord record : list){
				Customer customer = customerService.findOne(record.getCustomerId());
				smsService.sendRemainMsg(customer.getPhoneNo(), customer.getName() + "," + record.getProductName() + "," + sdf.format(record.getBookDate()));
				record.setStatus(BaseConstant.Status.VALID);
				bookRecordService.save(record);
			}
		}
	}
	
}
